// hooks/useVideoPlayer.js
import { ref, onUnmounted } from 'vue';

export const useVideoPlayer = () => {
  // 存储所有视频元素引用
  const videoRefs = ref([]);

  // 设置视频元素引用（index对应视频列表索引）
  const setVideoRef = (el, index) => {
    if (el) videoRefs.value[index] = el;
  };

  // 播放/暂停指定索引的视频（自动暂停其他视频）
  const toggleVideoPlay = (index) => {
    const targetVideo = videoRefs.value[index];
    if (!targetVideo) return;

    // 暂停所有其他视频
    videoRefs.value.forEach((video, i) => {
      if (video && i !== index && !video.paused) video.pause();
    });

    // 切换当前视频状态
    targetVideo.paused ? targetVideo.play().catch(err => {
      console.warn('视频自动播放失败（需用户交互）', err);
    }) : targetVideo.pause();
  };

  // 暂停所有视频
  const pauseAllVideos = () => {
    videoRefs.value.forEach(video => {
      if (video && !video.paused) video.pause();
    });
  };

  // 组件卸载时暂停所有视频（避免内存泄漏）
  onUnmounted(() => {
    pauseAllVideos();
  });

  return {
    videoRefs,
    setVideoRef,
    toggleVideoPlay,
    pauseAllVideos
  };
};